#include <stdio.h>
#ifdef WIN32
#include "windows.h"
#endif
#include <GL/gl.h>
#include <GL/glut.h>

#include "md_ver_1_0.h"

GLuint textureID = -1;
ModelData * md = 0;

struct Vertex
{
    float tu, tv;
    float x, y, z;
};

Vertex g_quadVertices[] =
{
    { 0.0f,0.0f, -1.0f,-1.0f, 0.0f },
    { 1.0f,0.0f,  1.0f,-1.0f, 0.0f },
    { 1.0f,1.0f,  1.0f, 1.0f, 0.0f },
    { 0.0f,1.0f, -1.0f, 1.0f, 0.0f }
};

void glutResize(int width, int height)
{
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
      /* modify this line to change perspective values */
	gluPerspective(45.0, (float)width/(float)height, 1.0, 700.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

int LoadRawCheckTexture()
{
	GLuint textureId = 0;
	unsigned char buffer[] = 	
	{
		0,0,255,		255,0,0,	0,0,
		255,0,0,		0,0,255,		0,0
	};

	glGenTextures(1, &textureId);

	glBindTexture(GL_TEXTURE_2D, textureId);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer);

	//Specify Filtering
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );


	return textureId;	
}

float rotate = 0.0f;

void glutDisplay(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
   // glTranslatef( 0.0f, -100.0f, -400.0f );
    glTranslatef( 0.0f, 0.0f, -20.0f );

	rotate += 1.0f;
	if(rotate > 360)
		rotate -= 360.0f;

	glRotatef(rotate,0,1,0);

	glEnable(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D,textureID);

	//glInterleavedArrays( ((MDVer1_0 *)md)->format, ((MDVer1_0 *)md)->stride, ((MDVer1_0 *)md)->data );
	//glDrawArrays( GL_TRIANGLES, 0, ((MDVer1_0 *)md)->size );
	for(int meshId =0; meshId < ((MDVer1_0 *)md)->totalMeshes; meshId ++)
	{
		glInterleavedArrays( ((MDVer1_0 *)md)->format, ((MDVer1_0 *)md)->stride, ((MDVer1_0 *)md)->data );
		glDrawArrays( ((MDVer1_0 *)md)->primitive , ((MDVer1_0 *)md)->meshes[meshId].dataOffset, ((MDVer1_0 *)md)->meshes[meshId].size );
	}
	//glInterleavedArrays( GL_T2F_V3F, 0, g_quadVertices );
	//glDrawArrays( GL_QUADS, 0, 4 );


    glFlush();
    glutSwapBuffers();
}

void Init()
{

}


void DoIdle()
{
  glutPostRedisplay();
}
int main(int argc, char** argv)
{
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA | GLUT_MULTISAMPLE );
    glutInitWindowPosition( 100, 100 );
    glutInitWindowSize( 300, 300 );
    glutInit( &argc, argv );

    glutCreateWindow("simpleogl");
	if(argc >= 2)
	{
		md = ModelDataLoad(argv[1]);
	}

	textureID = LoadRawCheckTexture();


	glutReshapeFunc(glutResize);
	glutDisplayFunc(glutDisplay);
	glutIdleFunc(DoIdle);

	glutMainLoop();
}

